<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>部门管理</title>
    <link rel="stylesheet" th:href="@{/css/admin/base.css}">
    <link rel="stylesheet" th:href="@{/lib/flatpickr/flatpickr.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
    <link rel="stylesheet" th:href="@{/lib/tree/zTreeStyle.css}" type="text/css">

</head>

<body class="page-device">
<div class=" app-page">
    <div class="app-page-header">
        <div class="page-title">
            <div class="title">部门</div>
        </div>
    </div>

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <!-- 过滤器 -->
                <div class="filter " style="display: none;" data-checkUser>
                    <!-- 选项切换 -->
                    <div class="form-item">
                        <div class="form-group">
                            <label for="">人员：</label>
                            <input type="text" placeholder="请输入用户姓名/手机/邮箱" name="search" class="search">
                        </div>
                    </div>

                    <button class="z-btn z-primary" id="doFilter">查询</button>
                </div>

                <div class="z-btn-group">
                    <button data-state="4" class="j-btn-control z-btn z-default add-dept z-hide" data-addDept>添加部门</button>
                    <button data-state="3" class="j-btn-control z-btn z-default edit-dept z-hide" data-editDept>编辑部门</button>
                    <button data-state="2" class="j-btn-control z-btn z-default add-account z-hide" data-addUser>添加用户</button>
                    <button data-state="1" class="j-btn-control z-btn z-default import z-hide" data-batchImport>批量导入</button>
                    <button data-state="1" class="j-btn-control z-btn z-default downloadTemp z-hide" data-batchImport>下载批量导入模板</button>
                    <input type="file" multiple name="file" class="z-hide">
                </div>

            </div>
        </div>

        <div class="app-card ">
            <div class="app-card-body z-df">
                <!-- 左侧 -->
                <div class="left-sidebar">
                    <div class="body">
                        <ul id="tree" class="ztree"></ul>
                    </div>
                </div>
                <!-- 列表数据 -->
                <div class="z-table-con">
                    <table class="z-table">
                        <thead>
                        <th>
                            <input type="checkbox" class="j-checkbox-all">
                        </th>
                        <th>账号</th>
                        <th>性别</th>
                        <th>部门</th>
                        <th>角色</th>
                        <th>姓名</th>
                        <th>邮箱</th>
                        <th>手机号</th>
                        <th>操作</th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div class="z-page z-pat">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加部门 -->
<div class="popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close></div>
    <!--添加部门 -->
    <div class="popup-add-dept section z-hide">
        <div class="title">添加部门</div>
        <div class="content" id="deptForm">
            <div class="form">
                <div class="form-item row">
                    <div class="label">
                        <label>父部门名称</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="parentId" name="parentId">
                        <button class="z-btn z-default select-btn select-dept">选择</button>
                    </div>
                </div>
                <div class="form-item z-hide">
                    <div class="label">
                        <label>部门ID</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="departmentId" name="departmentId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门名称</label>
                    </div>
                    <div class="body upload">
                        <input type="text" value="" class="departmentName" name="departmentName" data-name="部门" data-rule="required,length" minlength="6" maxlength="32">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门编码</label>
                    </div>
                    <div class="body upload" data-limit="0">
                        <input type="text" value="" class="departmentCode" name="departmentCode" data-name="部门编号" data-rule="length" minlength="6" maxlength="30">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门描述</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <textarea rows="10" placeholder="最多输入500字" class="description" name="description" data-name="部门描述" data-rule="length" minlength="2" maxlength="100"></textarea>
                    </div>
                </div>
            </div>
            <div class="z-btn-group">
                <a class="btn-sub z-btn z-primary dept-confirm">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
    <!--添加用户 -->
    <div class="popup-add-acount section z-hide">
        <div class="title">添加用户</div>
        <div class="content" id="userForm">
            <div class="form">
                <div class="form-item z-hide">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入姓名" class="userId" name='userId'>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>用户名</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入姓名" class="userName" name="userName" autocomplete="off" data-name="用户名" data-rule="required,length" minlength="5" maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>真实姓名</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入姓名" class="realName" name="realName" data-name="真实姓名" data-rule="length" maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>性别</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <select name="sex" class="sex">
                            <option value="0">女</option>
                            <option value="1">男</option>
                        </select>
                    </div>
                </div>

                <div class="form-item row">
                    <div class="label">
                        <label>登陆密码</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <input type="text" value="" placeholder="请输入登陆密码" class="password" name="password" autocomplete="off" data-name="登录密码" data-rule="required,length" minlength="6" maxlength="32">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>民族</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <select value="" class="nation" name="nation">
                            <option value="0">--请选择--</option>
                        </select>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>身份证</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <input type="text" value="" placeholder="请输入身份证" class="idCard" name="idCard">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>所属部门</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="departmentId z-hide" name='departmentId'>
                        <input type="text" value="" disabled="disabled" class="departmentName" name='departmentName'>
                        <button class="z-btn z-default select-btn select-dept">选择</button>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>岗位</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" class="post" name='post'>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="roleIds z-hide" name='roleIds'>
                        <input type="text" value="" disabled="disabled" class="roleNames" name='roleNames'>
                        <button class="z-btn z-default select-btn select-role">选择</button>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>邮箱</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入邮箱" class="email" name="email"></div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>手机号</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入手机号" class="telephone" name="telephone"></div>
                </div>
            </div>
            <div class="z-btn-group">
                <a class="btn-sub z-btn z-primary user-confirm">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
</div>

<div id="rMenu" class="rMenu">
    <ul class="rm-group rmg-1">
        <li id="mAddNode" onclick="addTreeNode('node');" data-addDept>添加子部门</li>
        <li id="mEditNode" onclick="editTreeNode('node');" data-editDept>编辑部门</li>
        <li id="mDel" onclick="removeTreeNode();" data-delDept>删除部门</li>
    </ul>
    <ul class="rm-group rmg-2">
        <li id="mAddRoot" onclick="addTreeNode('root');" data-addDept>添加根节点</li>
    </ul>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/upload.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/lib/tree/jquery.ztree.core-3.5.js}"></script>
<script th:src="@{/js/tree.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<!--加密-->
<script th:src="@{/lib/CryptoJS3/rollups/md5.js}"></script>
<script>

    var zTree = null,
        zTable = null,
        pageParams = {
            departmentId: '',
            // roleId: '',
            search: ''
        },
        deptOptType = 1,    // 1，添加  2，修改
        userOptType = 1,    // 1，添加  2，修改
        deptData = {},  // 暂存当前修改的部门信息
        userData = {},
        nations = null;

    var auth = {
        checkDept: false,
        addDept: false,
        checkUser: false,
        editDept: false,
        batchImport: false,
        addUser: false,
        delDept: false,
        enableUser: false,
        delUser: false
    };

    $(function () {

        pageParams = $.extend(true, pageParams, App.pageParams);

        //初始化按钮显示
        auth = $.extend(true, auth, App.initBtnView(top.authBtns || []));

        // 是否有批量导入的权限
        if (auth['batchImport']) {
            initUpload();
        }

        // 是否有查看部门的权限
        if (auth['checkDept']) {
            initTree();
        } else {
            $('.left-sidebar').html('抱歉，您现在没有查看部门的权限');
        }

        if (!auth['addDept']) {
            $('#mAddNode, #mAddRoot').remove();
        }
        if (!auth['editDept']) {
            $('#mEditNode').remove();
        }
        if (!auth['delDept']) {
            $('#mDel').remove();
        }

        // 是否有查看用户的权限
        if (auth['checkUser']) {
            initTable();
        } else {
            // 是否查看用户信息
            $('.z-table tbody').html('抱歉，您现在没有查看账号的权限');
        }

        getNation();

        eventListen();

    });

    function eventListen() {
        /**====== 事件监听 ======*/

        $(".import").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            $("input[name=file]").click();
        })

        $('#doFilter').click(function () {
            doSearchData();
        })

        $('.add-account').click(function () {

            userOptType = 1;
            App.clearForm('.popup-add-acount');
            popup.open('.popup-add-acount');
            $('.popup-add-acount .password').attr('data-rule','required,length');
        });

        $('.downloadTemp').click(function () {
            location.href = App.apiUrlHost + '/sysUser/downloadSysUserTemplate';
        });

        // 选择部门按钮
        $('.select-dept').click(function (e) {
            e.preventDefault();
            var $self = $(this);
            layerOpen({
                type: 1,
                title: '选择部门',
                url: '/page/selectDept',
                comfirm: (index, layero, layer) => {

                    var $ids = $(layero.find('iframe')).contents().find(".src-ids");
                    var $names = $(layero.find('iframe')).contents().find(".src-names");

                    var idshtml = $ids.html().replace(/\<br\>/g, ',');
                    var namehtml = $names.html().replace(/\<br\>/g, ',');
                    // alert('选取的角色id为：' + html);
                    $self.siblings('.departmentId').val(idshtml);
                    $self.siblings('.departmentName').val(namehtml);

                    layer.close(index);
                },
                cancel: (index, layero, layer) => {

                    layer.close(index);
                }
            })
        });

        // 选择角色
        $('.select-role').click(function (e) {
            e.preventDefault();
            var $self = $(this);
            layerOpen({
                type: 1,
                title: '选择角色',
                url: './selectRole.html',
                comfirm: (index, layero, layer) => {

                    var $ids = $(layero.find('iframe')).contents().find(".src-ids");
                    var $names = $(layero.find('iframe')).contents().find(".src-names");

                    var idshtml = $ids.html().replace(/\<br\>/g, ',');
                    var namehtml = $names.html().replace(/\<br\>/g, ',');
                    // alert('选取的角色id为：' + html);
                    $self.siblings('.roleIds').val(idshtml);
                    $self.siblings('.roleNames').val(namehtml);

                    layer.close(index);
                },
                cancel: (index, layero, layer) => {

                    layer.close(index);
                }
            })
        })

        // 添加、修改部门
        $('.add-dept,.edit-dept').click(function () {

            App.clearForm('.popup-add-dept');
            if ($(this).hasClass('edit-dept')) {
                deptOptType = 2;
            } else {
                deptOptType = 1;
            }
            // 检查选取数量
            // 修改时需要检测是否有选中的节点，并初始化数据
            if (deptOptType == 2) {

                if (!checkSelect()) return;

                var checkResult = zTree.tree.getSelectedNodes();

                // todo 获取需修改的数据
                getDept(checkResult[0].id, (result) => {

                    App.fillForm('.popup-add-dept', result);
                    $('.popup-add-dept .title').html('编辑部门');
                    $('.parentId').val(checkResult[0].pId);
                });


            } else {
                $('.popup-add-dept .title').html('添加部门');
            }

            popup.open('.popup-add-dept');
        });

        $("#deptForm").form({
            submitSelector: '.dept-confirm',
            msg: function (msg) {
                popup.tips(msg);
            },
            submit: function () {

                var data = {
                    'parentId': $('[name=parentId]').val() || '',
                    'departmentName': $('[name=departmentName]').val(),
                    'departmentCode': $('[name=departmentCode]').val(),       // 部门编码
                    'description': $('[name=description]').val(),
                    'sortCode': '', // 排序号
                    'able': 1
                };

                // var data = getData($("#deptForm"));

                var url = '';

                if (deptOptType == 1) {
                    url = App.apiUrlHost + '/sysDepartment/saveDepartment';
                    // 添加
                    submitDeptData(url, data, (result) => {
                        // 刷新树节点
                        doAddTreeNode({
                            id: result.departmentId,
                            isParent: false,
                            name: result.departmentName,
                            pId: result.parentId
                        });
                        popup.close('.popup-add-dept')
                    });
                } else {
                    url = App.apiUrlHost + '/sysDepartment/updateDepartment';

                    deptData['parentId'] = $('[name=parentId]').val();
                    deptData['departmentName'] = $('[name=departmentName]').val();
                    deptData['departmentCode'] = $('[name=departmentCode]').val();  // 部门编码
                    deptData['description'] = $('[name=description]').val();
                    // deptData['sortCode'] =  ''; // 排序号
                    // deptData['able'] =  1
                    deptData['departmentId'] = $('[name=departmentId]').val()
                    // 修改
                    submitDeptData(url, deptData, (result) => {
                        // 刷新树节点

                        replaceTreeNode({
                            id: result.departmentId,
                            name: result.departmentName,
                            pId: result.parentId
                        })

                        popup.close('.popup-add-dept')
                    });

                }

            }
        });

        $("#userForm").form({
            submitSelector: '.user-confirm',
            msg: function (msg) {
                popup.tips(msg);
            },
            submit: function () {

                var sysUser = {
                    'userId': $('.popup-add-acount [name=userId]').val(),
                    'departmentId': $('.popup-add-acount [name=departmentId]').val(),
                    'userName': $('.popup-add-acount [name=userName]').val(),       // 部门编码
                    // 'password': $('.popup-add-acount [name=password]').val(),
                    'realName': $('.popup-add-acount [name=realName]').val(),
                    'sex': $('.popup-add-acount [name=sex]').val(),
                    'post': $('.popup-add-acount [name=post]').val(),
                    'nation': $('.popup-add-acount [name=nation]').val(),
                    'idCard': $('.popup-add-acount [name=idCard]').val(),
                    'email': $('.popup-add-acount [name=email]').val(),
                    'telephone': $('.popup-add-acount [name=telephone]').val(),
                    'able': 1
                };

                // var sysUser = getData($("#userForm"));

                var pw = $('.popup-add-acount [name=password]').val();

                if (pw) {

                    sysUser['password'] = CryptoJS.MD5(pw).toString();
                }

                // 数据整合
                var data = {
                    sysUserJson: JSON.stringify(sysUser),
                    roleIds: $('.popup-add-acount [name=roleIds]').val()
                };

                if (userOptType == 1) {
                    var url = App.apiUrlHost + '/sysUser/saveSysUser';
                } else {
                    var url = App.apiUrlHost + '/sysUser/updateSysUser';

                    data.sysUserJson = JSON.stringify($.extend(true, userData, sysUser));
                }

                submitDeptData(url, data, (result) => {

                    popup.close('.popup-add-acount');

                    zTable.resetPage();
                    zTable.reload();

                });

            }
        });

    }

    function getData($form) {

        var data = {}


        $.each($form.eq(0).serializeArray(), function (index, field) {
            if (data[field.name]) {
                data[field.name] += "," + field.value;
            } else {
                data[field.name] = field.value;
            }
        })

        return data;
    }

    function initTable() {
        zTable = $('.z-table-con').pagination({
            $pageShowArea: $('.z-page'),
            async: {
                url: App.apiUrlHost + '/sysUser/listPage',// 请求地址
                dataType: 'json',
                type: 'POST',
                data: pageParams // 请求参数
            },
            beforAjax: function (data) {

                pageParams = $.extend(true, pageParams, App.getFilter());
                return {
                    departmentId: pageParams.departmentId,
                    search: pageParams.search,
                    pageNum: parseInt(data.start / pageParams.pageSize, 10) + 1
                }
            },
            columns: [
                {
                    className: 'j-checkbox-col',
                    width: '30px',
                    data: null,
                    render: function (data, type, row, meta) {
                        return '<input type="checkbox" class="j-checkbox" id="' + data.userId + '">';
                    }
                },
                {'data': 'userName', className: 'ellipsis'},
                {'data': 'sexDesc', className: 'ellipsis'},
                {'data': 'departmentName', className: 'ellipsis'},
                {'data': 'roleName', className: 'ellipsis'},
                {'data': 'realName', className: 'ellipsis'},
                {'data': 'email', className: 'ellipsis'},
                {'data': 'telephone', className: 'ellipsis'},
                {'data': 'status', className: 'ellipsis'},
            ],
            beforeCreateRow: function ($row, data, index) {

                var optHtml = '';

                if (auth['editUser']) {
                    optHtml += '<a href="#" classs="edit-acount" onclick="javascript:editUser(this)">编辑</a>';
                }
                if (auth['delUser']) {
                    optHtml += '<a href="#" onclick="javascript:delUser(this)">删除</a>';
                }
                if (auth['enableUser']) {

                    if (data.able == '1') {
                        optHtml += '<a href="#" onclick="javascript:disableUser(this)">停用</a>';
                    } else {
                        optHtml += '<a href="#" onclick="javascript:ableUser(this)">启用</a>';
                    }
                }


                $('td', $row).eq(8).html(optHtml);


                return $row;
            },
            drawCallback: function (setting) {
                // console.log('drawCallback');
            },
            initComplete: function (setting, json) {
                // console.log('initComplete');
            },
            formartData: function (data) {
                // console.log('formartData');

                return {
                    recordsTotal: data.data.total,
                    data: data.data.list,
                    // pageIndex: data.data.pageNum
                }
            }
        });

        zTable.init();
    }

    function initTree() {
        // 初始化树结构
        zTree = (new Tree).init({
            async: {
                url: App.apiUrlHost + '/sysDepartment/list',
            },
            callback: {
                onRightClick: zTreeOnRightClick,
                onClick: zTreeOnClick
            },
        });
    }

    function initUpload() {
        // 初始化上传
        uploadFiles = $(".z-btn-group").upload({
            fieldname: 'file',
            url: App.apiUrlHost + '/sysUser/importUserBatch',
            beforeSend: function () {
                const {$element, uploadId, file} = uploadFiles;
                const {uploadType, limit, inputName} = uploadFiles.options;

                const html = `
                            <div class="upload-item" data-id="${uploadId}">
                                <input type="text" name="${inputName}" class="z-hide">
                                <div class="head">
                                    <a class="name" target="_blank">${file.name}</a>
                                    <div class="close fa fa-close"></div>
                                </div>
                                <div class="progress">
                                    <div class="progress-outer">
                                        <div class="progress-inner">
                                            <div class="progress-bg" style="width: 0%; height: 8px;"></div>
                                        </div>
                                    </div>
                                    <div class="progress-text">0%</div>
                                </div>

                            </div>
                  `;

                if (limit == 1) {
                    $element.find('.upload-list').html(html);
                } else {
                    $element.find('.upload-list').append(html);
                }

                uploadFiles.$uploadName = $element.find(`.upload-item[data-id=${uploadId}] .name`);
                uploadFiles.$progress = $element.find(`.upload-item[data-id=${uploadId}] .progress`);
                uploadFiles.$progressBg = $element.find(`.upload-item[data-id=${uploadId}] .progress-bg`);
                uploadFiles.$progressText = $element.find(`.upload-item[data-id=${uploadId}] .progress-text`);
                uploadFiles.$inputFile = $element.find(`.upload-item[data-id=${uploadId}] input`);
            },
            success: function (result) {
                const {$element, uploadId} = uploadFiles;
                if (result.code == 0) {
                    zTable.init();
                    popup.tipsTop({type: 'success', msg: result.msg})
                    // progressSet(1, {url: result.data[0].file})
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                    // progressSet(2)
                }
            },
            error: function (err) {
                // progressSet(3, {msg: err})
            },
            progress: function ({percentage}) {
                // progressSet(0, {percentage})
            },
            recursion: true,
        })
    }

    // 获取民族
    function getNation() {
        App.getData({
            url: App.apiUrlHost + '/sysUser/listNation',
            data: {},
            dataType: 'json',
            success: function (result) {

                if (result.code == 0) {

                    nations = result.data;

                    var html = '';

                    for (var i = 0; i < nations.length; i++) {
                        html += '<option value="' + nations[i] + '">' + nations[i] + '</option>'
                    }

                    $('.popup-add-acount .nation').html(html);

                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

    // 帅选数据
    function doSearchData() {
        // pageParams = $.extend(true, pageParams, App.getFilter());

        // var selectDepts = Tree.tree.getSelectedNodes();
        // if (selectDepts && selectDepts.length > 0) {
        //     pageParams.departmentId = selectDepts[0].id;
        // }
        zTable.resetPage();
        zTable.reload();

    }

    // 删除用户
    function delUser(self) {

        if (confirm('确认是否删除？')) {

            var userId = $(self).parents('tr').find('.j-checkbox').attr('id');
            var url = App.apiUrlHost + '/sysUser/deleteSysUser';
            App.getData({
                url: url,
                data: {userId: userId},
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        zTable.init();

                        popup.tipsTop({type: 'success', msg: result.msg})

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })

        }

    }

    // 停用用户
    function disableUser(self) {

        if (confirm('确认是否停用')) {

            var userId = $(self).parents('tr').find('.j-checkbox').attr('id');
            var url = App.apiUrlHost + '/sysUser/disable';
            App.getData({
                url: url,
                data: {userId: userId},
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        zTable.init();

                        popup.tipsTop({type: 'success', msg: result.msg})

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })
        }

    }


    // 启用用户
    function ableUser(self) {

        if (confirm('确认是否启用')) {

            var userId = $(self).parents('tr').find('.j-checkbox').attr('id');
            var url = App.apiUrlHost + '/sysUser/enable';
            App.getData({
                url: url,
                data: {userId: userId},
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        zTable.init();

                        popup.tipsTop({type: 'success', msg: result.msg})

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })
        }

    }

    // 编辑用户
    function editUser(self) {

        userOptType = 2;

        //todo 获取当前选中用户信息
        var userId = $(self).parents('tr').find('.j-checkbox').attr('id');
        var url = App.apiUrlHost + '/sysUser/getById';
        App.getData({
            url: url,
            data: {userId: userId},
            dataType: 'json',
            success: function (result) {

                if (result.code == 0) {

                    userData = result.data;
                    App.fillForm('.popup-add-acount', result.data);
                    $('.popup-add-acount [name=sex]').val(result.data.sex);
                    $('.popup-add-acount [name=password]').val('');
                    $('.popup-add-acount [name=roleIds]').val(result.data.roleId);
                    $('.popup-add-acount [name=roleNames]').val(result.data.roleName);
                    popup.open('.popup-add-acount');

                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })

    }

    // 检测选中数量
    function checkSelect() {
        var checkResult = zTree.tree.getSelectedNodes();

        if (checkResult.length <= 0) {
            popup.tipsTop({type: 'warning', msg: '请选择要修改的部门'})
            return false;
        } else {
            console.log('选择数量检测成功');
            return true;
        }
    }

    // 提交部门信息
    function submitDeptData(url, data, callback) {

        App.getData({
            url: url,
            data: data,
            dataType: 'json',
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    callback(result.data);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

    //节点右击
    function zTreeOnRightClick(event, treeId, treeNode) {
        if (!treeNode && event.target.tagName.toLowerCase() != 'button' && $(event.target).parents('a').length == 0) {
            zTree.tree.cancelSelectedNode();
            zTree.showRMenu('root', event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            zTree.tree.selectNode(treeNode);
            zTree.showRMenu('node', event.clientX, event.clientY);
        }
    }

    // 树节点被点击事件
    function zTreeOnClick(event, treeId, treeNode) {

        var treeNodeID = treeNode.id;

        // if (!treeNode.isParent) {
        // 叶子节点，刷新列表数据
        pageParams.departmentId = treeNodeID;
        zTable.resetPage();
        zTable.reload();
        // }
    }

    // 右键菜单添加字节点
    function addTreeNode(type) {
        zTree.hideRMenu();

        deptOptType = 1;

        var nodes = zTree.tree.getSelectedNodes();

        var title = type === 'root' ? '添加根部门' : '添加子部门',
            pid = (nodes && nodes.length && type === 'node') ? nodes[0].id : '',
            pname = (nodes && nodes.length && type === 'node') ? nodes[0].name : 'ROOT';

        App.clearForm('.popup-add-dept');
        $('.popup-add-dept .title').html(title);
        $('.parentId').val(pid);
        popup.open('.popup-add-dept');

    }

    function doAddTreeNode(newNode) {
        zTree.hideRMenu();
        if (zTree.tree.getSelectedNodes() && zTree.tree.getSelectedNodes().length > 0) {
            newNode.checked = zTree.tree.getSelectedNodes()[0].checked;
            zTree.tree.addNodes(zTree.tree.getSelectedNodes()[0], newNode);
        } else {
            zTree.tree.addNodes(null, newNode);
        }
    }

    // 右键菜单编辑节点
    function editTreeNode() {

        deptOptType = 2;

        zTree.hideRMenu();
        var nodes = zTree.tree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            var id = nodes[0].id,
                pId = nodes[0].pId;

            getDept(id, (result) => {
                App.fillForm('.popup-add-dept', result);
                $('.popup-add-dept .title').html('编辑部门');
                $('.parentId').val(pId);
                popup.open('.popup-add-dept');
            })

        }
    }

    // 替换节点
    function replaceTreeNode(newNode) {
        //获取当前节点
        zTree.tree.getSelectedNodes()[0].name = newNode.name;
        zTree.tree.getSelectedNodes()[0].id = newNode.id;
        zTree.tree.getSelectedNodes()[0].pId = newNode.pId;
        zTree.tree.updateNode(zTree.tree.getSelectedNodes()[0])
    }

    // 删除节点
    function removeTreeNode() {
        zTree.hideRMenu();
        var nodes = zTree.tree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            if (nodes[0].children && nodes[0].children.length > 0) {
                var msg = '要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！';
                if (confirm(msg) == true) {
                    if (confirm('真的要删除吗？') == true) {
                        doDelNode(nodes[0].id, function () {
                            zTree.tree.removeNode(nodes[0]);
                        });
                    }
                }
            } else {
                doDelNode(nodes[0].id, function () {
                    zTree.tree.removeNode(nodes[0]);
                });
            }
        }
    }

    function doDelNode(id, callback) {
        App.getData({
            url: App.apiUrlHost + '/sysDepartment/deleteDepartment',
            dataType: 'json',
            data: {departmentId: id},
            success: function (result) {

                if (callback && typeof callback === 'function') {
                    callback(result);
                }
            }
        });
    }

    // 获取到树结构时对数据进行处理
    function filter(treeId, parentNode, data) {

        if (data.code == 0) {

            data.data = JSON.parse(JSON.stringify(data.data).replace(/parentId/g, 'pId'));
            data.data = JSON.parse(JSON.stringify(data.data).replace(/departmentId/g, 'id'));
            data.data = JSON.parse(JSON.stringify(data.data).replace(/departmentName/g, 'name'))

            var childNodes = data.data;

            return childNodes;
        } else {

            return null;
        }

    }

    function getDept(id, callback) {

        App.getData({
            url: App.apiUrlHost + '/sysDepartment/getById',
            data: {departmentId: id},
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    deptData = result.data;
                    callback(result.data);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

</script>
<script th:src="@{/lib/flatpickr/flatpickr.js}"></script>
<script th:src="@{/lib/flatpickr/zh.js}"></script>
<script>
    flatpickr.localize(flatpickr.l10ns.zh); // 设置为中文
    flatpickr(".flatpickr-hour", {
        enableTime: true,
        noCalendar: true,
        dateFormat: "H:i",
        time_24hr: true
    });
</script>
</body>